<template>
  <div>
    <Hearder />
    <el-card>
      <el-alert title="添加商品信息" center show-icon type="info"> </el-alert>

      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRefs"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeTab"
          @tab-click="getCateGories"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="goodsList"
                :props="addGoodsList"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1"
            >商品参数
            <el-form-item
              :label="item.attr_name"
              prop="goods_number"
              v-for="(item, i) in addData"
              :key="i"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="a"
                  v-for="(a, b) in item.attr_vals"
                  :key="b"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form>
              <el-form-item
                :label="item.attr_name"
                v-for="(item, i) in shoppingList"
                :key="i"
              >
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="getuploadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addWrite">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="提示" :visible.sync="dialogVisible">
      <span slot="footer" class="dialog-footer">
        <img :src="formUrl" alt="" class="imageItem" />
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      dialogVisible: false,
      formUrl: "",
      headersObj: {
        Authorization: JSON.parse(window.localStorage.getItem("token")),
      },
      upload: "http://127.0.0.1:8888/api/private/v1/upload",
      shoppingList: [],
      addData: [],
      goodsList: [],
      addGoodsList: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      addForm: {
        attrs: [],
        goods_introduce: "",
        pics: [],
        goods_cat: [],
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
      },
      addRules: {
        goods_cat: [{ required: true, message: "商品分类", trigger: "blur" }],
        goods_number: [
          { required: true, message: "商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "商品重量", trigger: "blur" },
        ],
        goods_name: [{ required: true, message: "商品名称", trigger: "blur" }],
        goods_price: [{ required: true, message: "商品价格", trigger: "blur" }],
      },
      activeIndex: 0,
    };
  },
  computed: {
    addId() {
      return this.addForm.goods_cat[2];
    },
  },
  methods: {
    addWrite() {
     this.$refs.addFormRefs.validate(async valid => {
             if (!valid) return this.$message.error('提交信息有误')
        // 会报错使用lodash 中的cloneDeep深拷贝
        // this.addForm.goods_cat = this.addForm.goods_cat.join(",");
        const from = _.cloneDeep(this.addForm);
        from.goods_cat = from.goods_cat.join(",");
        this.shoppingList.map((item) => {
          const addInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addForm.attrs.push(addInfo);
        });
        from.attrs = this.addForm.attrs;

        
        this.addData.map((item) => {
          const addInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addForm.attrs.push(addInfo);
        });
        from.attrs = this.addForm.attrs;
       
            
        const { data: res } = await this.$http
          .post("goods", from)
          .catch((err) => err);
            if(res.meta.status!==201)return this.$Message.success('商品创建失败')
            console.log(666,res);
          this.$router.push('/goods')
      });
    },
    getuploadSuccess(response) {
        console.log(response);
      const picsInfo = { pic: response.data.tmp_path };
      this.addForm.pics.push(picsInfo);
    },
    handleRemove(file) {
      // 两个数组比较不相等产生一个新数组
      this.addForm.pics = this.addForm.pics.filter(
        x => x.pic !== file.response.data.tmp_path
      );
    },
    handlePreview(file) {
      console.log(999,file);
      this.formUrl = file.response.data.url;
      this.dialogVisible = true;
    },
    async getCateGories() {
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http
          .get(`categories/${this.addId}/attributes`, {
            params: { sel: "many" },
          })
          .catch((err) => err);

        res.data.map(
          (item) =>
            (item.attr_vals =
              item.attr_vals.length === 0 ? [] : item.attr_vals.split(" "))
        );
        this.addData = res.data;


      }
      if (this.activeIndex === "2") {
        const { data: res } = await this.$http
          .get(`categories/${this.addId}/attributes`, {
            params: { sel: "only" },
          })
          .catch((err) => err);
        this.shoppingList = res.data;
       
      }
    },
    beforeTab(activeName, oldActiveName) {
      //  为false 就会中断
      if (
        (oldActiveName === "0" && !this.addForm.goods_name) ||
        (oldActiveName === "0" && this.addForm.goods_cat.length !== 3)
      ) {
        this.$Message.error("资料未填写完毕");
        return false;
      }
    },
    handleChange(val) {
      console.log(this.addForm.goods_cat[2]);
      console.log(22, val);
    },
    async getList() {
      const { data: res } = await this.$http
        .get("categories")
        .catch((err) => err);
    
      this.goodsList = res.data;
    },
  },
  mounted() {
    this.getList();
  },
};
</script>

<style scoped>
.imageItem {
  max-width: 100%;
}
.el-steps {
  margin: 20px auto !important;
}
.el-steps >>> .el-step__title {
  font-size: 14px !important;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}

.el-button {
  margin-top: 10px;
}
</style>
